package utsc.apps.utschedule;

import java.util.ArrayList;

import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

import utsc.apps.utschedule.R;
import utsc.apps.utschedule.classes.Course;
import utsc.apps.utschedule.classes.Timetable;
import utsc.apps.utschedule.ui.MessageDialogFragment;
import utsc.apps.utschedule.ui.activities.GenericFragmentActivity;
import utsc.apps.utschedule.ui.activities.LoginActivity;
import utsc.apps.utschedule.ui.activities.SyncCourseTask;
import utsc.apps.utschedule.ui.interfaces.OnSyncListener;
import utsc.apps.utschedule.ui.interfaces.TimetableActivity;
import utsc.apps.utschedule.util.AppUtils;
import utsc.apps.utschedule.util.TimetableHelper;
import utsc.apps.utschedule.util.database.DatabaseManager;

import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.Toast;

public class UTSCheduleHomeActivity extends GenericFragmentActivity implements OnSyncListener<Course>{
    
	/** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //getWindow().setFormat(PixelFormat.RGBA_8888);
        setContentView(R.layout.main);
    }
    
    @Override
    protected void onDestroy() {
    	super.onDestroy();
    	unbindDrawables(findViewById(R.id.home_layout));
    	//Log.d(this.getClass().getName(), "unbind drawables");
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	getSupportMenuInflater().inflate(R.menu.search_menu, menu);
    	if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            SearchManager searchManager =
                    (SearchManager) getSystemService(Context.SEARCH_SERVICE);
            android.widget.SearchView searchView =
                    ( android.widget.SearchView) menu.findItem(R.id.search).getActionView();
            searchView.setSearchableInfo(
                    searchManager.getSearchableInfo(getComponentName()));
            searchView.setIconifiedByDefault(false);
        }
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.search:
            	if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
            		onSearchRequested();
            	}
            	return true;
            case R.id.sync:
            	
		        //check the network state
		        if (AppUtils.checkNetworkState(this)) {
	            	if (((UTSCheduleApp)getApplication()).get_currentActiveTimetable()!=null) {
	            		if (AppUtils.hasLoginPreferences(this)) {
	            			new SyncCourseTask(this, TimetableHelper.getCurrentTermString()).execute(AppUtils.getLoginPreferences(this));
	            		}else {
	            			Intent syncIntent=new Intent(this,LoginActivity.class);
	            			startActivityForResult(syncIntent,TimetableActivity.RESULT_SYNC_COURSE);
	            		}
					}else {
						showDialogFragment(MessageDialogFragment.newInstance("Warning - Sync", "Please setup a timetable before syncing your courses."), MessageDialogFragment.TAG);
					}
	            }else {
	            	showDialogFragment(MessageDialogFragment.newInstance("ERROR - Network", "No network connection available."), MessageDialogFragment.TAG);
	            }
            	
                return true;
            default:
                return false;
        }
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    	if (keyCode == KeyEvent.KEYCODE_SEARCH) {
    		onSearchRequested();
		}
    	return super.onKeyDown(keyCode, event);
    }
    
    @Override
    protected void onResume() {
    	super.onResume();
    	UTSCheduleApp app=((UTSCheduleApp)getApplication());
    	ArrayList<Course> courses=app.get_syncedCourses();
    	if (courses!=null&&!courses.isEmpty()) {
    		onSyncCompleted(courses);
    		app.set_syncedCourses(null);
		}
    	
    }

	@Override
	public void onSyncCompleted(ArrayList<Course> result) {
		if (result!=null&& !result.isEmpty()) {
			UTSCheduleApp app=(UTSCheduleApp) getApplication();
			Timetable timetable=app.get_currentActiveTimetable();
			if (timetable!=null) {
				
				DatabaseManager.getInstance(this).saveSyncCourse(timetable.get_timetableID(), result);
				app.refreshCurrentTimetable();
				timetable.refreshCourseList();
				if (app.get_syncedCourses()==null) {
					Toast.makeText(this, "Sync is completed", Toast.LENGTH_SHORT).show();
				}
			}else {
				showDialogFragment(MessageDialogFragment.newInstance("Error - Sync", "We are unable to sync your courses. It could be related to login account or your intranet profile. Please try again later."), MessageDialogFragment.TAG);
			}
		}
	}
    
}